package com.example.add

import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.add.constant.RouteAddConstant
import com.tencent.live2.V2TXLiveCode.V2TXLIVE_ERROR_INVALID_LICENSE
import com.tencent.live2.V2TXLiveDef
import com.tencent.live2.V2TXLivePusher
import com.tencent.live2.impl.V2TXLivePusherImpl
import com.tencent.rtmp.ui.TXCloudVideoView


@Route(path = RouteAddConstant.ROUTE_ADD_ACTIVITY)
class AddActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.add_activity_add)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }


        // 指定对应的直播协议为 RTMP，该协议不支持 连麦
        val mLivePusher: V2TXLivePusher =
            V2TXLivePusherImpl(this, V2TXLiveDef.V2TXLiveMode.TXLiveMode_RTMP)

        // 启动本地摄像头预览
        val mPusherView = findViewById<View>(R.id.txcv_push_show) as TXCloudVideoView
        mLivePusher.setRenderView(mPusherView)
        mLivePusher.startCamera(true)
        mLivePusher.startMicrophone()

        val startPushButton : Button = findViewById(R.id.btn_start_push)
        val stopPushButton : Button = findViewById(R.id.btn_stop_push)
        startPushButton.setOnClickListener {
            mLivePusher.startPush("rtmp://192.168.1.101:1935/live/test")
            // 根据推流协议传入对应的 URL 即可启动推流， RTMP 协议以 rtmp:// 开头，该协议不支持连麦
            val url = "rtmp://test.com/live/streamid?txSecret=xxxxx&txTime=xxxxxxxx"

            // 根据推流协议传入对应的 URL 即可启动推流， RTC 协议以 trtc:// 开头，该协议支持连麦
            //val url = "trtc://cloud.tencent.com/push/streamid?sdkappid=1400188888&userId=A&usersig=xxxxx"
            val ret = mLivePusher.startPush(url)

            // 推流失败
            if (ret == V2TXLIVE_ERROR_INVALID_LICENSE) {
                Log.i(TAG, "startRTMPPush: license 校验失败")
                Toast.makeText(this,  "startRTMPPush: license 校验失败", Toast.LENGTH_SHORT)
                    .show()
            }
        }
        stopPushButton.setOnClickListener {
            // 结束推流
            mLivePusher.stopPush();
        }
    }
}